package com.aaron.demo1.test.megaeyes.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import com.aaron.demo1.test.megaeyes.model.MegaEyes;
import com.aaron.demo1.test.megaeyes.model.SecondAuthticationReq;
import com.aaron.demo1.test.megaeyes.model.SecondAuthticationRsp;
import com.aaron.demo1.test.megaeyes.model.TokenCreateReq;
import com.aaron.demo1.test.megaeyes.service.ApiService;
import com.aaron.demo1.test.megaeyes.util.AuthenticationUtils;
import com.alibaba.fastjson.JSON;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


/**
 * 全球眼接口service层
 *
 * @author wangmj
 * @date 2020/04/28
 */

@Service
public class ApiServiceImpl implements ApiService {
    private static final Logger logger = LoggerFactory.getLogger(ApiServiceImpl.class);

    private static final String GET_TOKEN_URL = "/videoService/accounts/authorize";

    private String token = "";

    private static final String DEVICE_TREE = "/videoService/devicesManager/deviceTree";


//    @Autowired
//    private RedisTemplate redisTemplate;

//    @Autowired
//    private VideoEquipmentInfoMapper videoEquipmentInfoMapper;
//
//    @Autowired
//    private MegaEyesMapper megaEyesMapper;
    /**
     * 全球眼获取token
     *
     * @return token
     * @author wangmj
     */
    @Override
    public String getToken(String lesseeId) {
//        MegaEyes megaEye = this.getMegaEyeByLessId(lesseeId);
        MegaEyes megaEye = new MegaEyes();
        megaEye.setUsername("AdminJQR");
        megaEye.setPassword("Zqqqy1357");
        megaEye.setClientType("winpc");
        megaEye.setUrl("https://61.151.156.1:8282");
        if (StringUtils.isEmpty(megaEye.getUsername()) || StringUtils.isEmpty(megaEye.getPassword())) {
            return "";
        }
        try {
            TokenCreateReq req = new TokenCreateReq();
            req.setClientType(megaEye.getClientType());
            req.setUserName(megaEye.getUsername());

            String requestUrl = megaEye.getUrl() + GET_TOKEN_URL;
            String reqJson = JSON.toJSONString(req);
            logger.info("获取token，requestUrl:{}，req:{}", requestUrl, reqJson);
//        String result = HttpRequest.post(requestUrl).setProxy(proxy).body(reqJson).execute().body();
            String result = HttpRequest.post(requestUrl).body(reqJson).timeout(1000*4).execute().body();
            logger.info("全球眼第一次请求获取结果：{}", result);
            //修复持续登录报错问题
            if (result.contains("encryptType")) {
                //把第一次请求的结果放到第二次请求中
                SecondAuthticationReq request = JSON.parseObject(result, SecondAuthticationReq.class);
                request.setPassword(megaEye.getPassword());
                request.setUserName(megaEye.getUsername());
                request.setClientType(megaEye.getClientType());

                String username = request.getUserName();
                String password = request.getPassword();
                //域信息
                String realm = request.getRealm();
                //随机密钥
                String randomKey = request.getRandomKey();
                //加密类型 默认MD5
                String encryptType = request.getEncryptType();
                String signature = AuthenticationUtils.getSignature(username, password, realm, randomKey, encryptType);
                request.setSignature(signature);

                logger.info("getToken request:{}", JSON.toJSONString(request));

//            String result2 = HttpRequest.post(property.getUrl() + GET_TOKEN_URL).setProxy(proxy).body(JSON.toJSONString(request)).execute().body();
                String result2 = HttpRequest.post(megaEye.getUrl() + GET_TOKEN_URL).body(JSON.toJSONString(request)).timeout(1000*4).execute().body();
                logger.info("getToken response:{}", result2);
                SecondAuthticationRsp response = JSON.parseObject(result2, SecondAuthticationRsp.class);
                token = response.getToken();
                logger.info("MegaEyesToken:{}", token);
//                redisTemplate.opsForValue().set("MegaEyesToken" + megaEye.getUsername(), token);
            }
        } catch (Exception e) {
            logger.error("全球眼获取token失败", e);
        }
        if (StringUtils.isEmpty(token)) {
//            token = (String) redisTemplate.opsForValue().get("MegaEyesToken" + megaEye.getUsername());
        }
        return token;
    }

    @Override
    public List<Map<String, Object>> getChannelId(String nodeId, String lesseeId) {
        String token = getToken(lesseeId);
        MegaEyes megaEye = new MegaEyes();
        megaEye.setUsername("AdminJQR");
        megaEye.setPassword("Zqqqy1357");
        megaEye.setClientType("winpc");
        megaEye.setUrl("https://61.151.156.1:8282");
        if (StringUtils.isEmpty(nodeId)) {
            //先获取根组织Id
            String rootUrl = megaEye.getUrl() + DEVICE_TREE + "?id=&nodeType=1&typeCode=01&page=1&pageSize=4";
            String rootResponse = HttpRequest.get(rootUrl).header("X-Subject-Token", token).timeout(1000*4).execute().body();
            Map<String, Object> rootRsp = JSON.parseObject(rootResponse, Map.class);
            List<Map<String, Object>> rootResult = (List<Map<String, Object>>) rootRsp.get("results");
            nodeId = (String) rootResult.get(0).get("id");
        }
        //获取根组织下的通道列表 //也可以用typeCode=01;1;ALL;ALL获取设备和通道列表
        String deviceTreeUrl = megaEye.getUrl() + DEVICE_TREE + "?id=" + nodeId + "&nodeType=1&typeCode=01;0;ALL;ALL&page=1&pageSize=32";
        String response = HttpRequest.get(deviceTreeUrl).header("X-Subject-Token", token).execute().body();
        Map<String, Object> rsp = JSON.parseObject(response, Map.class);
        List<Map<String, Object>> arr = (List<Map<String, Object>>) rsp.get("results");
        //枚举所有通道类型的编码值
        return arr;
    }
//
//    /**
//     * 获取直播流
//     *
//     * @return MonitorUrlRsp
//     * @author wangmj
//     */
//    @Override
//    public String getRealMonitor(String channelId, String scheme,String lesseeId) {
//        logger.info("获取直播流lesseeId:{},channeId:{},scheme:{}",lesseeId,channelId,scheme);
//        String token = getToken(lesseeId);
//        String monitorUrl = "";
//        if (StringUtils.isNullOrEmpty(token)) {
//            return monitorUrl;
//        }
//        MegaEyes megaEye = this.getMegaEyeByLessId(lesseeId);
//        //默认获取m3u8格式数据
//        if (StringUtils.isNullOrEmpty(scheme)) {
//            scheme = "HLS";
//        }
//        if (StringUtils.isNotNullOrEmpty(channelId)) {
//            String realMonitorUrl = megaEye.getUrl() + REAL_MONITOR + "?channelId=" + channelId + "&scheme=" + scheme + "&subType=0";
////            String body = HttpRequest.get(realMonitorUrl).setProxy(proxy).header("X-Subject-Token", token).execute().body();
//            String body = HttpRequest.get(realMonitorUrl).header("X-Subject-Token", token).timeout(1000*4).execute().body();
//            logger.info("getRealMonitor response:{}", body);
//
//            MonitorUrlRsp monitorUrlRsp = JSON.parseObject(body, MonitorUrlRsp.class);
//            monitorUrl = monitorUrlRsp.getUrl();
//        }
//        return monitorUrl;
//    }
//
//    /**
//     * 获取设备直播流
//     *
//     * @param equipmentList 设备列表
//     * @return List<EquipmentMonitorV2> 获取直播流的设备列表
//     * @author gonghj
//     */
//    @Override
//    public List<EquipmentInfo> getRealMonitorList(List<EquipmentInfo> equipmentList,String lesseeId) {
//
//        //判断设备列表中是否全部未填写存储通道
//        boolean flag = equipmentList.stream().anyMatch(equipmentInfo -> StringUtils.isNotNullOrEmpty(equipmentInfo.getStorageChannel()));
//        if(!flag) {
//            return equipmentList;
//        }
//        String token = getToken(lesseeId);
//        if (StringUtils.isNullOrEmpty(token)) {
//            return equipmentList;
//        }
//        MegaEyes megaEye = this.getMegaEyeByLessId(lesseeId);
//        if (equipmentList != null && equipmentList.size() > 0) {
//            for (EquipmentInfo equip : equipmentList) {
//                try {
//                    if (StringUtils.isNotNullOrEmpty(equip.getStorageChannel())) {
//                        String realMonitorUrl = megaEye.getUrl() + REAL_MONITOR + "?channelId=" + equip.getStorageChannel() + "&scheme=HLS";
//                        logger.info("获取实时视频流url:{}", realMonitorUrl);
//                        //                        String body = HttpRequest.get(realMonitorUrl).setProxy(proxy).header("X-Subject-Token", token).execute().body();
//                        String body = HttpRequest.get(realMonitorUrl).header("X-Subject-Token", token).timeout(1000*4).execute().body();
//                        MonitorUrlRsp monitorUrlRsp = JSON.parseObject(body, MonitorUrlRsp.class);
//                        logger.info("全球眼返回结果：{}", body);
//                        logger.info("通道号{}获取的实时视频流地址：{}", equip.getStorageChannel(), monitorUrlRsp.getUrl());
//                        equip.setRemark2(monitorUrlRsp.getUrl());
//                    }
//                } catch (Exception e) {
//                    logger.error("设备" + equip.getEquipmentId() + "获取实时视频流失败", e);
//                }
//            }
//        }
//        return equipmentList;
//    }
//
//    /**
//     * 根据组织获取通道channelId
//     *
//     * @param nodeId 组织id
//     * @return 通道编码
//     * @author gonghj
//     */
//    @Override
//    public List<Map<String, Object>> getChannelId(String nodeId,String lesseeId) {
//        String token = getToken(lesseeId);
//        MegaEyes megaEye = this.getMegaEyeByLessId(lesseeId);
//        if (StringUtils.isNullOrEmpty(nodeId)) {
//            //先获取根组织Id
//            String rootUrl = megaEye.getUrl() + DEVICE_TREE + "?id=&nodeType=1&typeCode=01&page=1&pageSize=4";
//            String rootResponse = HttpRequest.get(rootUrl).header("X-Subject-Token", token).timeout(1000*4).execute().body();
//            Map<String, Object> rootRsp = JSON.parseObject(rootResponse, Map.class);
//            List<Map<String, Object>> rootResult = (List<Map<String, Object>>) rootRsp.get("results");
//            nodeId = (String) rootResult.get(0).get("id");
//        }
//        //获取根组织下的通道列表 //也可以用typeCode=01;1;ALL;ALL获取设备和通道列表
//        String deviceTreeUrl = megaEye.getUrl() + DEVICE_TREE + "?id=" + nodeId + "&nodeType=1&typeCode=01;0;ALL;ALL&page=1&pageSize=32";
//        String response = HttpRequest.get(deviceTreeUrl).header("X-Subject-Token", token).execute().body();
//        Map<String, Object> rsp = JSON.parseObject(response, Map.class);
//        List<Map<String, Object>> arr = (List<Map<String, Object>>) rsp.get("results");
//        //枚举所有通道类型的编码值
//        return arr;
//    }
//
//    /**
//     * 根据设备id查询设备实时视频流
//     *
//     * @param equipment 设备查询条件
//     * @return 设备实时视频流
//     */
//    @Override
//    public VideoEquipmentInfo getChannelVideo(EquipmentInfo equipment) {
//        Example example = new Example(VideoEquipmentInfo.class);
//        Example.Criteria criteria = example.createCriteria();
//
//        criteria.andEqualTo("id", equipment.getId());
//        VideoEquipmentInfo videoEquipmentInfo = videoEquipmentInfoMapper.selectOneByExample(example);
//        return videoEquipmentInfo;
//    }
//
//    public MegaEyes getMegaEyeByLessId(String lesseeId){
//        logger.info("获取租户lesseeId:{}全球眼配置信息",lesseeId);
//        if (StringUtils.isBlank(lesseeId)){
//            return  new MegaEyes();
//        }
//        Example example = new Example(MegaEyes.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("state",1);
//        criteria.andEqualTo("belongLesseeId",lesseeId);
//
//        List<MegaEyes> megaEyes = megaEyesMapper.selectByExample(example);
//        if (CollectionUtil.isNotEmpty(megaEyes)) {
//            MegaEyes megaEyes1 = megaEyes.get(0);
//            megaEyes1.setPassword(Base64.decodeStr(megaEyes1.getPassword()));
//            logger.info("租户lesseeId:{}的全球眼配置:{}",lesseeId, JSON.toJSON(megaEyes1));
//            return megaEyes1;
//        }
//        return new MegaEyes();
//    }
}
